package edu.neumont.csc380.ttt.game;

import java.util.Scanner;

/*
 * TicTacToe Game
 *
 * Author: Brooks
 *
 */

/**
 * This class contains the game logic using the board and player objects.
 */
public class Game {

	private Board board;
	private int turn = 1, player = 1;
	private Player player1;
	private Player player2;
	public Scanner input = new Scanner(System.in);

	public Game() {
		board = new Board();
		assignPlayers();

		while (Play());
	}

	//this logic is here to support AI
	public void assignPlayers() {
		System.out.println("Who will be player1 ?");
		if (choosePlayer() == 1)
			this.player1 = new Human(1);
		else		
			this.player1 = new Human(1);
		
		System.out.println("Who will be Player 2 ?");

		if (choosePlayer() == 1)
			this.player2 = new Human(2);
		else
			this.player2 = new Human(2);

	}

	public int choosePlayer() {
		int option = 0;

		do {
			System.out.println("1. Human");
			System.out.println("2. AI [NOT IMPLEMENTED]\n");
			System.out.print("Option: ");
			option = input.nextInt();
			//&& option != 2
			if (option != 1 )
				System.out.println("Invalid Option: Try again");
		} while (option != 1 );

		return option;
	}

	public boolean Play() {
		board.printBoard();
		if (won() == 0) {
			
			System.out.println("\nTurn " + turn);
			System.out.println("It's turn of Player " + player());

			if (player() == 1)
				player1.play(board);
			else
				player2.play(board);

			if (board.full()) {
				System.out.println("Full Board. Tie!");
				return false;
			}
			player++;
			turn++;

			return true;
		} else {
			if (won() == -1)
				System.out.println("Player 1 won!");
			else
				System.out.println("Player 2 won!");

			return false;
		}

	}

	public int player() {
		if (player % 2 == 1)
			return 1;
		else
			return 2;
	}

	public int won() {
		if (board.checkRows() == 1)
			return 1;
		if (board.checkColumns() == 1)
			return 1;
		if (board.checkDiagonals() == 1)
			return 1;

		if (board.checkRows() == -1)
			return -1;
		if (board.checkColumns() == -1)
			return -1;
		if (board.checkDiagonals() == -1)
			return -1;

		return 0;
	}

}
